<?php
namespace app\swoole\model;

use app\common\ParseCrontab;

class ScheduleTask extends \think\Model {
    /**
     * 取数时转换任务的状态值
     * @param int $val  原始值
     * @return sting
     */
//    public function getStatusAttr($val) {
//        $status = [0 => '关闭', 1 => '开启'];
//        return isset($status[$val]) ? $status[$val] : '关闭';
//    }    

    /**
     * 保存的时候，将数组转换为逗号分隔的字符串
     * @param mixed $weeks  定时的周字段
     * @return type
     */
    public function setWeekAttr($weeks) {
        if (is_array($weeks)) {
            sort($weeks);
            return implode(',', $weeks);
        }
        return (string) $weeks;
    }

    /**
     * 获取需要注册的任务
     * @param int $next_start_timestamp 下次执行的时间戳
     * @return array 返回需要运行的任务列表
     */
    static public function needRegister($next_start_timestamp) {
        $task_list = self::all(['status' => 1]);
        $data_time = date('Y-m-d H:i:00', $next_start_timestamp);
        $need_register_task = [];
        foreach ($task_list as $task) {
            $task['plan_start_time'] = $data_time;
            if (ParseCrontab::parse($task, $next_start_timestamp) === FALSE) {
                continue;
            }
            unset($task['minute'], $task['hour'], $task['day'], $task['month'], $task['week']);
            $need_register_task[] = $task;
        }
        unset($task_list);
        return $need_register_task;
    }

}
